<template>
    <view class="container">
        <view class="fishing-bg">
            <view class="joystick-container">
                <canvas id="joystick" type="2d" class="joystick-canvas" style="width: 200px; height: 200px;"
                    @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd"></canvas>
            </view>
            <view class="fishing-area">
                <fishingArea :originAngle="angle" />
            </view>
            <view class="status-info">
                <text>方向: {{ direction }}</text>
                <text>力度: {{ power.toFixed(1) }}%</text>
            </view>
        </view>
    </view>
</template>

<script>
import fishingArea from './components/fishingArea.vue';
export default {
    components: { fishingArea },
    data() {
        return {
            canvas: null,
            ctx: null,
            centerX: 0,
            centerY: 0,
            radius: 60,
            stickRadius: 30,
            isTouching: false,
            touchX: 0,
            touchY: 0,
            direction: "中间",
            power: 0,
            angle: 0,
            // 新增：用于平滑过渡的角度缓存
            targetAngle: 0,
            angleDamping: 0.2 // 角度过渡阻尼（0~1，越小过渡越平滑）
        };
    },
    onReady() {
        this.initCanvas();
        // 启动角度平滑过渡动画
        this.startAngleTween();
    },
    methods: {
        initCanvas() {
            const query = uni.createSelectorQuery().in(this);
            query
                .select("#joystick")
                .node()
                .exec((res) => {
                    const canvas = res[0].node;
                    const ctx = canvas.getContext("2d");

                    // 设置 DPR 分辨率
                    const dpr = uni.getSystemInfoSync().pixelRatio;
                    const width = 200;
                    const height = 200;
                    canvas.width = width * dpr;
                    canvas.height = height * dpr;
                    ctx.scale(dpr, dpr);

                    this.canvas = canvas;
                    this.ctx = ctx;
                    this.centerX = width / 2;
                    this.centerY = height / 2;

                    this.drawJoystick();
                    this.startAngleTween();
                });
        },

        drawJoystick() {
            const ctx = this.ctx;
            if (!ctx) return;

            ctx.clearRect(0, 0, 200, 200);

            // 绘制外圆
            ctx.beginPath();
            ctx.arc(this.centerX, this.centerY, this.radius, 0, 2 * Math.PI);
            ctx.fillStyle = "rgba(0,0,0,.2)";
            ctx.fill();
            ctx.strokeStyle = "rgba(0,0,0,0.2)";
            ctx.lineWidth = 2;
            ctx.stroke();

            // 内圆（摇杆）
            let stickX = this.centerX;
            let stickY = this.centerY;

            if (this.isTouching) {
                const dx = this.touchX - this.centerX;
                const dy = this.touchY - this.centerY;
                const distance = Math.sqrt(dx * dx + dy * dy);

                if (distance > this.radius - this.stickRadius) {
                    const scale = (this.radius - this.stickRadius) / distance;
                    stickX = this.centerX + dx * scale;
                    stickY = this.centerY + dy * scale;
                } else {
                    stickX = this.touchX;
                    stickY = this.touchY;
                }

                this.updateStatus(dx, dy, distance);
            }

            ctx.beginPath();
            ctx.arc(stickX, stickY, this.stickRadius, 0, 2 * Math.PI);
            ctx.fillStyle = "rgba(0,0,0,.1)";
            ctx.fill();
            ctx.strokeStyle = "rgba(0,0,0,.1)";
            ctx.lineWidth = 2;
            ctx.stroke();
        },

        updateStatus(dx, dy, distance) {
            this.power = Math.min((distance / (this.radius - this.stickRadius)) * 100, 100);

            // 计算角度（弧度转角度）
            const radian = Math.atan2(dy, dx);
            let angle = radian * 180 / Math.PI;

            // 关键优化：基于当前角度计算差值，而非从0开始
            const currentAngleDeg = this.angle * 180; // 将当前归一化角度转回度数
            let diff = angle - currentAngleDeg;

            // 处理跨180°边界的最短路径问题
            if (diff > 180) {
                angle -= 360;
            } else if (diff < -180) {
                angle += 360;
            }

            // 映射角度到[-1, 1]范围（左负右正）
            let normalizedAngle = angle / 180;
            normalizedAngle = Math.max(-1, Math.min(1, normalizedAngle)); // 限制范围

            // 存储目标角度（基于当前角度继续移动）
            this.targetAngle = normalizedAngle;

            // 更新方向文本（保持不变）
            // ...


            // 更新方向文本
            if (distance < 10) {
                this.direction = "中间";
            } else if (angle > -22.5 && angle <= 22.5) {
                this.direction = "右";
            } else if (angle > 22.5 && angle <= 67.5) {
                this.direction = "右下";
            } else if (angle > 67.5 && angle <= 112.5) {
                this.direction = "下";
            } else if (angle > 112.5 && angle <= 157.5) {
                this.direction = "左下";
            } else if (angle > 157.5 || angle <= -157.5) {
                this.direction = "左";
            } else if (angle > -157.5 && angle <= -112.5) {
                this.direction = "左上";
            } else if (angle > -112.5 && angle <= -67.5) {
                this.direction = "上";
            } else if (angle > -67.5 && angle <= -22.5) {
                this.direction = "右上";
            }
        },

        // 角度平滑过渡动画
        startAngleTween() {
            const update = () => {
                if (this.isTouching) {
                    // 触摸时继续平滑过渡到目标角度
                    const diff = this.targetAngle - this.angle;
                    this.angle += diff * this.angleDamping;
                } else {
                    // 松手时保持当前角度，不再自动归位
                    // 移除自动回中逻辑：this.angle += (0 - this.angle) * this.angleDamping * 2;
                }
                if (this.canvas) {
                    this.canvas.requestAnimationFrame(update);
                }
            };
            update();
        },

        onTouchStart(e) {
            this.isTouching = true;
            this.touchX = e.touches[0].x;
            this.touchY = e.touches[0].y;

            // 触摸开始时，基于当前角度初始化目标角度
            this.targetAngle = this.angle;
            this.drawJoystick();
        },
        onTouchMove(e) {
            this.touchX = e.touches[0].x;
            this.touchY = e.touches[0].y;
            this.drawJoystick();
        },
        onTouchEnd() {
            this.isTouching = false;
            // 保留位置
            // this.power = 0;
            // this.direction = "中间";
            this.drawJoystick();
        },
    },
};
</script>


<style scoped>
.container {
    width: 100%;
    height: 100vh;
    overflow: hidden;
}

.fishing-bg {
    width: 100%;
    height: 100%;
    position: relative;
    z-index: 33;
}

/* 摇杆容器固定在右下角 */
.joystick-container {
    position: fixed;
    left: 30rpx;
    bottom: 30rpx;
    width: 200px;
    height: 200px;
    z-index: 300;
}

.joystick-canvas {
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

/* 状态信息显示 */
.status-info {
    position: fixed;
    top: 50rpx;
    left: 50rpx;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    display: flex;
    flex-direction: column;
    gap: 10rpx;
}

/* 钓鱼区域 */
.fishing-area {
    position: relative;
    z-index: 0;
}
</style>